package indi.zhang.common.branchs;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class HandleBeanProcessor implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (bean instanceof AbstraceHandle && bean.getClass().isAnnotationPresent(HandleTypes.class)) {
            Class<?> aClass = bean.getClass();
            //获取注解配置beans并从spring中根据beanName获取到bean注入到策略beans
            HandleTypes annotation = aClass.getAnnotation(HandleTypes.class);
            String[] values = annotation.values();
            if (null != values && values.length > 0) {
                List<Handle> handles = Arrays.stream(values).map(name -> {
                    Handle handle = (Handle) applicationContext.getBean(name);
                    return handle;
                }).collect(Collectors.toList());
                ((AbstraceHandle)bean).setHandleList(handles);
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}
